﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace DreamCMS.WebCore.Common
{
    public class Encryption
    {
        /// <summary>
        /// 对字符串进行MD5加密
        /// </summary>
        /// <param name="input">待加密的字符串</param>
        /// <returns>加密后的字符串</returns>
        public static string GetMd5Hash(string input)
        {
            //加盐处理
            string salt = "DreamCMSCYJ";
            input = input.Trim() + salt;
            //准备一个md5对象
            MD5 md5Hash = MD5.Create();
            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.Default.GetBytes(input));
            
            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            // Return the hexadecimal string.
            return sBuilder.ToString();
        }

 
        /// <summary>
        /// code 为加密位数，16和32。其Security命名空间需要引入system.Web库组件
        /// </summary>
        /// <param name="input">待加密的字符串</param>
        /// <param name="codeDigits">加密位数</param>
        /// <returns></returns>
       
        public static string GetMd5ConfigHash(string input, int codeDigits)
        {
            //加盐处理
            string salt = "DreamCMSCYJ";
            input = input.Trim() + salt;
            //str = System.Web.HttpUtility.UrlEncode(str);  
            if (codeDigits == 16) //16位MD5加密（取32位加密的9~25字符）  
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(input, "MD5").ToLower().Substring(8, 16);
            }
            if (codeDigits == 32) //32位加密  
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(input, "MD5").ToLower();
            }
            return "00000000000000000000000000000000";
        }

    }
}